package cn.iocoder.yudao.module.picturebook.utils;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;

import javax.net.ssl.SSLContext;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

/**
 * 音频处理工具类（JDK 1.8 兼容）
 * 提供 HTTPS 客户端创建、网络请求配置等辅助方法
 */
public class AudioProcessingUtils {

    // 超时时间配置（单位：毫秒）
    private static final int CONNECT_TIMEOUT = 5000;    // 连接超时
    private static final int SOCKET_TIMEOUT = 10000;    // 读取超时
    private static final int CONNECTION_REQUEST_TIMEOUT = 3000; // 请求等待超时

    /**
     * 创建支持 HTTPS 的客户端（跳过证书校验，适合测试环境）
     * 生产环境需移除证书信任逻辑，使用正规 SSL 证书
     */
    public static CloseableHttpClient createHttpsClient() {
        try {
            // 1. 构建 SSL 上下文：信任所有证书（仅测试用）
            SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, (X509Certificate[] chain, String authType) -> true)
                    .build();

            // 2. 配置请求超时参数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(CONNECT_TIMEOUT)
                    .setSocketTimeout(SOCKET_TIMEOUT)
                    .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
                    .build();

            // 3. 构建 HttpClient 并设置参数
            return HttpClientBuilder.create()
                    .setSSLContext(sslContext)
                    .setSSLHostnameVerifier((hostname, session) -> true) // 跳过主机名校验
                    .setDefaultRequestConfig(requestConfig)
                    .build();

        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
            // 封装异常信息，便于定位问题
            throw new RuntimeException("创建 HTTPS 客户端失败：" + e.getMessage(), e);
        }
    }

    /**
     * 创建带代理的 HTTPS 客户端（如需通过代理访问音频资源）
     *
     * @param proxyHost 代理主机地址
     * @param proxyPort 代理端口
     */
    public static CloseableHttpClient createHttpsClientWithProxy(String proxyHost, int proxyPort) {
        CloseableHttpClient baseClient = createHttpsClient();
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);

        return HttpClientBuilder.create()
                .setDefaultRequestConfig(
                        RequestConfig.custom()
                                .setProxy(proxy)
                                .build()
                )
                .build();
    }

}